﻿using System;
using System.Collections.Generic;
using System.Xml;
using AlipaySDK.Dto;
using AlipaySDK.Dto.BizModel;
using AlipaySDK.Dto.Message;
using Aop.Api;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Util;

namespace AlipaySDK.Helper
{
    public class SendMessage
    {
        /// <summary>
        /// 发送文本信息给用户
        /// </summary>
        /// <param name="openId">支付宝openId</param>
        /// <param name="content">文本内容</param>
        /// <param name="appId">服务窗Id</param>
        /// <returns></returns>
        public static SendTextResponse SendText(string appId,string openId,string content)
        {

           SendTextBizContent bizContent = new SendTextBizContent();
            bizContent.createTime = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
            bizContent.msgType = "text";
            bizContent.toUserId = openId;
            bizContent.text = new SendTextBizContent.Text()
            {
                content = content
            };

            AlipayMobilePublicMessageCustomSendRequest pushRequst = new AlipayMobilePublicMessageCustomSendRequest();
            pushRequst.BizContent = Newtonsoft.Json.JsonConvert.SerializeObject(bizContent);
            Dictionary<string, string> paramsDict = (Dictionary<string, string>)pushRequst.GetParameters();
            IAopClient client = new DefaultAopClient(AopConfig.serverUrl, appId, AopConfig.merchant_private_key);
            AlipayMobilePublicMessageCustomSendResponse pushResponse = client.Execute(pushRequst);
            var responseBody = pushResponse.Body;
            return new SendTextResponse
            {
                ResultCode = pushResponse.Code == "200" ? "0" : "-1",
                ResultMsg = pushResponse.Msg,
                Body = responseBody
            };

        }

        /// <summary>
        /// 发送图文信息给用户
        /// </summary>
        /// <param name="appId">服务窗Id</param>
        /// <param name="openId">支付宝openId</param>
        /// <param name="articles">图文列表</param>
        /// <returns></returns>
        public static SendPhotoResponse SendPhoto(string appId,string openId, List<SendPhotoBizContent.Article> articles)
        {
            SendPhotoBizContent bizContent = new SendPhotoBizContent();
            bizContent.createTime = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
            bizContent.msgType = "image-text";
            bizContent.toUserId = openId;
            bizContent.articles = articles ?? new List<SendPhotoBizContent.Article>();
            AlipayMobilePublicMessageCustomSendRequest pushRequst = new AlipayMobilePublicMessageCustomSendRequest();
            pushRequst.BizContent = Newtonsoft.Json.JsonConvert.SerializeObject(bizContent); ;
            Dictionary<string, string> paramsDict = (Dictionary<string, string>)pushRequst.GetParameters();
            IAopClient client = new DefaultAopClient(AopConfig.serverUrl, appId, AopConfig.merchant_private_key);
            AlipayMobilePublicMessageCustomSendResponse pushResponse = client.Execute(pushRequst);
            var responseBody = pushResponse.Body;

            return new SendPhotoResponse
            {
                ResultCode = pushResponse.Code == "200" ? "0" : "-1",
                ResultMsg = pushResponse.Msg,
                Body = responseBody
            };

        }
        /// <summary>
        /// 发送模板信息
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="bizContent"></param>
        /// <returns></returns>

        public static BaseResponse SendTemplate(string appId,string bizContent)
        {

            AlipayMobilePublicMessageSingleSendRequest pushRequst = new AlipayMobilePublicMessageSingleSendRequest();
            pushRequst.BizContent = bizContent;
            Dictionary<string, string> paramsDict = (Dictionary<string, string>)pushRequst.GetParameters();
            IAopClient client = new DefaultAopClient(AopConfig.serverUrl, appId, AopConfig.merchant_private_key);
            AlipayMobilePublicMessageSingleSendResponse pushResponse = client.Execute(pushRequst);
            var responseBody = pushResponse.Body;
            return new BaseResponse
            {
                ResultCode = pushResponse.Code == "200" ? "0" : "-1",
                ResultMsg = pushResponse.Msg,
            };
        }


        /// <summary>
        /// 回复给用户的图文消息转换成官方接口格式（xml）
        /// </summary>
        /// <param name="appId">服务窗Id</param>
        /// <param name="openDirectUrl"></param>
        /// <param name="openId">服务窗openId</param>
        /// <returns>回复支付宝xmk字符串</returns>
        public static string ReceivemsgResponse(string appId,string openDirectUrl, string openId)
        {
            XmlDocument xmlDoc = new XmlDocument(); //创建实例
            XmlDeclaration xmldecl = xmlDoc.CreateXmlDeclaration("1.0", "GBK", null);
            xmlDoc.AppendChild(xmldecl);
            XmlElement xmlElem = xmlDoc.CreateElement("alipay"); 
            XmlElement response = xmlDoc.CreateElement("response");

            XmlElement subxml = xmlDoc.CreateElement("XML");
            string strsubxml =
                "<ToUserId><![CDATA[" + openId + "]]></ToUserId>";
            strsubxml += "<AppId><![CDATA[" + appId + "]]></AppId>";
            strsubxml += "<CreateTime>" + ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000)/10000000) +
                         "</CreateTime>";
            //strsubxml += "<MsgType><![CDATA[ack]]></MsgType>";
            strsubxml += "<MsgType><![CDATA[image-text]]></MsgType>";
            if (!string.IsNullOrEmpty(openDirectUrl))
            {
                strsubxml += "<ArticleCount>1</ArticleCount>";
                strsubxml += "<ShowType>open_direct</ShowType>";
                strsubxml += "<Articles>";
                strsubxml += "<Item>";
                strsubxml += "<Title><![CDATA[绑定]]></Title>";
                strsubxml += "<Desc><![CDATA[添加绑定]]></Desc>";
                strsubxml += "<ImageUrl><![CDATA[http://alipay.com/ima/2013.jpg]]></ImageUrl>";
                strsubxml += "<Url><![CDATA[" + openDirectUrl + "]]></Url>";
                strsubxml += "</Item>";
                strsubxml += "</Articles>";
                strsubxml += "<Push><![CDATA[false]]></Push>";
            }

            //subxml.InnerText = System.Net.WebUtility.HtmlEncode(strsubxml);
            subxml.InnerXml = strsubxml;
            response.AppendChild(subxml);
            xmlElem.AppendChild(response);
            string _sign = AlipaySignature.RSASign(response.InnerXml, AopConfig.merchant_private_key, AopConfig.charset);
            XmlElement sign = xmlDoc.CreateElement("sign");
            sign.InnerText = _sign;
            xmlElem.AppendChild(sign);
            XmlElement signType = xmlDoc.CreateElement("sign_type");
            signType.InnerText = "RSA";
            xmlElem.AppendChild(signType);

            xmlDoc.AppendChild(xmlElem); 
            return xmlDoc.InnerXml;
        }

        /// <summary>
        /// 发送匹配模板消息
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="url"></param>
        /// <param name="templateId"></param>
        /// <returns></returns>
        public static SendAuthMatchTemplateResponse SendAuthMatchTemplate(string appId,string mobile,string url,string templateId)
        {

            SendTemplateBizContent bizContent = new SendTemplateBizContent();
            bizContent.matcher = new SendTemplateBizContent.Matcher
            {
                mobileNo = mobile
            };
            //todo 赋值模板Id，以及消息明细
            bizContent.template = new SendTemplateBizContent.Template
            {
                templateId = templateId,
                context = new SendTemplateBizContent.Context
                {
                    headColor = "#85be53",
                    url = url,
                    keyword1 = new SendTemplateBizContent.Keyword
                    {
                        value = "",
                        color = "#000000"
                    },
                    keyword2 = new SendTemplateBizContent.Keyword
                    {
                        value = "",
                        color = "#000000"
                    },
                    keyword3 = new SendTemplateBizContent.Keyword
                    {
                        value = "",
                        color = "#000000"
                    },
                }
            };

            AlipayMobilePublicMessageMatcherSendRequest pushRequst = new AlipayMobilePublicMessageMatcherSendRequest();
            pushRequst.BizContent = Newtonsoft.Json.JsonConvert.SerializeObject(bizContent);
            Dictionary<string, string> paramsDict = (Dictionary<string, string>)pushRequst.GetParameters();
            IAopClient client = new DefaultAopClient(AopConfig.serverUrl, appId, AopConfig.merchant_private_key);
            AlipayMobilePublicMessageMatcherSendResponse pushResponse = client.Execute(pushRequst);
            var responseBody = pushResponse.Body;
            return new SendAuthMatchTemplateResponse
            {
                ResultCode = pushResponse.Code == "200" ? "0" : "-1",
                ResultMsg = pushResponse.Msg,
                Body = responseBody
            };
        }
    }
}
